package com.puppy.filter;

import com.puppy.utils.JWTUtils;
import com.puppy.utils.ThreadLocalUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
@WebFilter("/*")
public class TokenFilter implements Filter {

    /*init和destory方法被自动实现了的*/
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//      ServletRequest和ServletResponse都是接口，本质 HttpServletRequest extends ServletRequest,强转
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        //1.获取请求的路径
        String path = req.getRequestURI(); // /login

        //2.判断-是登录则不进行令牌校验，放行其去登录；
        if (path.contains("/login")) {
            log.info("登录请求，放行");
            chain.doFilter(req, resp);
            return;
        }

        //3.获取Token
        String token = req.getHeader("token");

        //4.判断token是否存在，token不存在，用户没有登录，返回错误信息401
        if (token == null || token.isEmpty()) {
            log.info("用户未登录，请先登录，令牌：{}", token);
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//            resp.setStatus(401);
            return;
        }
        // 5.token存在，则校验-校验失败401
        try {
            //校验token
            Claims claims = JWTUtils.parseJwt(token);//自己定义的工具类JWTUtils解析token,返回解析结果claims-map数组
            //将解析结果放到线程变量区 ,通过键”id“，得到值，强转为Integer类型
            ThreadLocalUtils.setCurrentLocal((Integer) (claims.get("id")));
            log.info("令牌校验成功，用户id：{},将其存入ThreadLocal", ThreadLocalUtils.getCurrentLocal());
        } catch (Exception e) {
            log.info("令牌校验失败，响应401");
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        }
        //6.校验成功则放行
        log.info("令牌校验成功，放行");
        chain.doFilter(req, resp);
        //7.释放资源.删除ThreadLocal的数据
        ThreadLocalUtils.removeCurrentLocal();
    }
}
